package com.example.demo.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AlternateConsumers {
    // 消息数组
    private static final String[] MESSAGES = {
        "Message 1", "Message 2", "Message 3", "Message 4", 
        "Message 5", "Message 6", "Message 7", "Message 8"
    };
    
    // 共享资源
    private static final Lock lock = new ReentrantLock();
    private static final Condition consumer1Turn = lock.newCondition();
    private static final Condition consumer2Turn = lock.newCondition();
    private static int currentIndex = 0;
    private static boolean isConsumer1Turn = true;

    public static void main1(String[] args) {
        // 创建并启动两个消费者线程
        Thread consumer1 = new Thread(() -> consumeMessages(true), "Consumer-1");
        Thread consumer2 = new Thread(() -> consumeMessages(false), "Consumer-2");
        
        consumer1.start();
        consumer2.start();
        
        try {
            consumer1.join();
            consumer2.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        System.out.println("All messages have been consumed!");
    }
    
    private static void consumeMessages(boolean isConsumer1) {
        while (true) {
            lock.lock();
            try {
                // 等待轮到自己消费
                while ((isConsumer1 && !isConsumer1Turn) || (!isConsumer1 && isConsumer1Turn)) {
                    if (isConsumer1) {
                        consumer1Turn.await();
                    } else {
                        consumer2Turn.await();
                    }
                }
                
                // 检查是否还有消息可消费
                if (currentIndex >= MESSAGES.length) {
                    // 通知另一个消费者也结束
                    if (isConsumer1) {
                        consumer2Turn.signal();
                    } else {
                        consumer1Turn.signal();
                    }
                    break;
                }
                
                // 消费消息
                String message = MESSAGES[currentIndex++];
                System.out.println(Thread.currentThread().getName() + ": " + message);
                
                // 切换到另一个消费者
                isConsumer1Turn = !isConsumer1Turn;
                if (isConsumer1) {
                    consumer2Turn.signal();
                } else {
                    consumer1Turn.signal();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(true || false);
    }
}
